package com.example.shiyansan.controller.admin;

import com.example.shiyansan.result.Result;
import com.example.shiyansan.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    //由于工具类已经被创建了可以直接注入进来
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的扩展名,表示从最后一个.的位置截取到最后
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString()+extension;
            String filepath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("文件上传失败");
    }
}
